<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">车牌号码：</span>
      <el-input v-model="params.carNumber" clearable placeholder="请输入内容" class="search-main" />
      <span class="search-label">车主姓名：</span>
      <el-input v-model="params.personName" clearable placeholder="请输入内容" class="search-main" />
      <span class="search-label">状态：</span>
      <el-select v-model="params.cardStatus" clearable placeholder="请选择状态">
        <el-option v-for="item in cardStatusLit" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>
      <el-button type="primary" class="search-btn" @click="doSearch">查询</el-button>
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/cardAdd')">添加月卡</el-button>
      <el-button @click="delCartList">批量删除</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="cardList" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column type="index" label="序号" />
        <el-table-column label="车主名称" prop="personName" />
        <el-table-column label="联系方式" prop="phoneNumber" />
        <el-table-column label="车牌号码" prop="carNumber" />
        <el-table-column label="车辆品牌" prop="carBrand" />
        <el-table-column label="剩余有效天数" prop="totalEffectiveDate" />
        <el-table-column label="状态" prop="cardStatus" :formatter="formatStatus" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button size="mini" type="text">续费</el-button>
            <el-button size="mini" type="text">查看</el-button>
            <el-button size="mini" type="text" @click="editCard(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delCard(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :page-size="params.pageSize"
        :total="total"
        :current-page="params.page"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { getCardDetailAPI, getCardListAPI, updateCardAPI, createCardAPI, delCardListAPI } from '@/api/user'
import { delCardAPI } from '@/api/user'

export default {
  data() {
    return {
      // 已选择列表
      selectedCarList: [],
      editCard(id) {
        this.$router.push({
          path: '/cardAdd',
          query: {
            id
          }
        })
      },
      // 请求参数
      params: {
        page: 1,
        pageSize: 5,
        cardStatus: null, // 状态
        carNumber: null, // 车牌号码
        personName: null // 车主姓名
      },
      // 月卡状态
      cardStatusLit: [
        { id: null, name: '全部' },
        { id: 0, name: '可用' },
        { id: 1, name: '已过期' }
      ],
      // 总数
      total: 0,
      // 月卡列表
      cardList: []
    }
  },
  // 获取详情
  async getDetail() {
    const res = await getCardDetailAPI(this.id)
    console.log(res)
    // 回填茶凉信息表单
    const { carInfoId, personName, phoneNumber, carNumber, carBrand } = res.data
    this.formData = {
      carInfoId,
      personName,
      phoneNumber,
      carNumber,
      carBrand
    }
    // 回填缴费信息表单
    const { rechargeId, cardStartDate, cardEndDate, paymentAmount, paymentMethod } = res.data
    this.formData = {
      rechargeId,
      paymentAmount,
      paymentMethod,
      payTime: [cardStartDate, cardEndDate]
    }
  },
  mounted() {
    if (this.id) {
      this.getDetail()
    }
    this.getCardList()
  },
  methods: {
    handleSelectionChange(rowList) {
      console.log(rowList)
      this.selectedCarList = rowList
    },
    delCartList() {
      this.$confirm('此操作将永久删除选择的月卡, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 处理id
        await delCardListAPI(this.selectedCarList.map(item => item.id))
        this.getCardList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    // 根据id做接口适配
    confirmAdd() {
      this.$refs.carInfoForm.validate(valid => {
        if (valid) {
          this.$refs.feeForm.validate(async valid => {
            if (valid) {
              // 全部校验通过
              // 参数处理
              const payload = {
                ...this.feeForm,
                ...this.carInfoForm,
                cardStartDate: this.feeForm.payTime[0],
                cardEndDate: this.feeForm.payTime[1]
              }
              delete payload.payTime
              if (this.id) {
                // 编辑
                await updateCardAPI(payload)
              } else {
                await createCardAPI(payload)
              }
              this.$router.back()
            }
          })
        }
      })
    },
    // 批量删除
    // 格式化状态
    formatStatus(row) {
      const MAP = {
        0: '可用',
        1: '已过期'
      }
      return MAP[row.cardStatus] || '未知'
    },
    // 删除逻辑
    delCard(id) {
      console.log('Deleting card with ID:', id) // 添加调试信息
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delCardAPI(id) // 调用删除API
          console.log('Card deleted successfully') // 添加调试信息
          this.getCardList() // 刷新列表
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } catch (error) {
          console.error('Error deleting card:', error) // 打印错误信息
          this.$message({
            type: 'error',
            message: '删除失败，请稍后再试!'
          })
        }
      }).catch(() => {
        console.log('User canceled deletion') // 用户取消删除
      })
    },
    // 获取月卡列表
    async getCardList() {
      try {
        const res = await getCardListAPI(this.params)
        this.cardList = res.data.rows // 更新列表数据
        this.total = res.data.total // 更新总数
      } catch (error) {
        console.error('Error fetching card list:', error) // 打印错误信息
        this.$message({
          type: 'error',
          message: '获取列表失败，请稍后再试!'
        })
      }
    },
    // 分页切换
    pageChange(page) {
      this.params.page = page // 更新当前页码
      this.getCardList() // 刷新列表
    },
    // 查询
    doSearch() {
      this.params.page = 1 // 重置为第一页
      this.getCardList() // 刷新列表
    }
  }
}
</script>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
  .search-btn{
    margin-left:20px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
